package com.softeem.score.manager.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.softeem.score.common.exception.MyException;
import com.softeem.score.manager.mapper.ClassesMapper;
import com.softeem.score.manager.mapper.StudentMapper;
import com.softeem.score.manager.service.ClassesService;
import com.softeem.score.model.dto.ClassesDto;
import com.softeem.score.model.entity.ClassesEntity;
import com.softeem.score.model.entity.school.Classes;
import com.softeem.score.model.vo.common.ResultCodeEnum;
import com.softeem.score.model.vo.school.ClassesVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zhu
 * @since 2024-02-14
 */
@Service
public class ClassesServiceImpl implements ClassesService {

    @Autowired
    private ClassesMapper classesMapper;

    @Autowired
    private StudentMapper studentMapper;


    @Override
    public PageInfo<ClassesVo> findByPage(ClassesDto classesDto, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ClassesVo> classesVos = classesMapper.findByPage(classesDto);
        for (ClassesVo classesVo : classesVos) {
            classesVo.setHeadcount(studentMapper.findCountByClassesId(classesVo.getId()));
        }
        return new PageInfo<>(classesVos);
    }

    @Override
    public List<ClassesEntity> findAllClasses(Long collegeId, Long majorId) {
        return classesMapper.selectAllClasses(collegeId, majorId);
    }

    @Transactional
    @Override
    public void saveClasses(Classes classes) {
        classesMapper.saveClasses(classes);
    }

    @Transactional
    @Override
    public void updateClasses(Classes classes) {
        if (classes.getMajorId() != classesMapper.findMajorIdByClassesId(classes.getId())) {
//            schedulesMapper.deleteByClassesId(classes.getId());
        }
        classesMapper.updateClasses(classes);
    }

    @Transactional
    @Override
    public void deleteById(Long classesId) {
        if (studentMapper.findCountByClassesId(classesId) > 0) {
            throw new MyException(ResultCodeEnum.CLASSE_NOT_DELETE);
        }
        classesMapper.deleteById(classesId);
//        schedulesMapper.deleteByClassesId(classesId);
    }

//    @Transactional
//    @Override
//    public void updateSchedules(Schedules schedule) {
//        Schedules schedules = schedulesMapper.findByCourseIdAndClassesId(schedule.getCourseId(), schedule.getClassesId());
//        System.out.println("schedules........... = " + schedules);
//        if (schedules != null) {
//            schedulesMapper.updateSchedules(schedule);
//        } else {
//            schedulesMapper.saveSchedules(schedule);
//        }
//    }


}
